﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Xml.Linq;
using RelightERP.DAL.EntityModel;
using RelightERP.BLL;
using RelightERP.BO.Entities;

public partial class Admin_UserControls_Branch : System.Web.UI.UserControl
{
    MasterHelper masterHelper = null;

    #region EVENT HANDLERS

    protected void Page_Init(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            using (RelightDBEntities context = new RelightDBEntities())
            {
                LoadDataSource(context);
            }
            if (masterHelper == null) masterHelper = new MasterHelper();
        }
    }

    protected void Page_Load(object sender, EventArgs e)
    {

    }

    protected void btnSave_Click(object sender, EventArgs e)
    {
        Utility.HideMsgDiv(divMsg);
        Utility.HideMsgDiv(divErr);

        if (btnSave.CommandName == "InsertBranch")
        {
            InsertBranch();
        }
        else if (btnSave.CommandName == "UpdateBranch")
        {
            int branchID = 0;
            int.TryParse(btnSave.CommandArgument, out branchID);
            UpdateBranch(branchID);
        }
    }

    protected void gvBranches_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        int branchID = 0;
        if (e.CommandName.ToUpper() == "EDITBRANCH")
        {            
            int.TryParse(e.CommandArgument.ToString(), out branchID);
            if (branchID > 0)
            {
                LoadSelectedBranchDetails(branchID);
            }
        }
        else if (e.CommandName.ToUpper() == "DELETEBRANCH")
        { 
            int.TryParse(e.CommandArgument.ToString(), out branchID);
            if (branchID > 0)
            {
                using (RelightDBEntities context = new RelightDBEntities())
                {
                    Branches selectedBranch = context.Branches.FirstOrDefault(x => x.BranchID == branchID);
                    if (selectedBranch != null) 
                    {
                        context.Branches.DeleteObject(selectedBranch);
                        context.SaveChanges();
                        LoadDataSource(context);
                        mpeViewBranches.Show();
                    }
                }
            }
        }
    }

    protected void btnCancel_Click(object sender, EventArgs e)
    {
        btnNew_Click(sender, e);
    }

    protected void btnNew_Click(object sender, EventArgs e)
    {
        ResetForm();
        Utility.HideMsgDiv(divMsg);
        Utility.HideMsgDiv(divErr);
        tbBranchName.Focus();

    }

    protected void lnkbtnDeleteBranches_Click(object sender, EventArgs e)
    {
        //IList<int> selectedBranchList = new List<int>();
        //int branchID = 0;
        //foreach (GridViewRow row in gvBranches.Rows)
        //{
        //    if (row.RowType == DataControlRowType.DataRow)
        //    {
        //        if ((row.Cells[0].FindControl("chkSelectRow") as CheckBox).Checked)
        //        {
        //            branchID = 0;
        //            int.TryParse(gvBranches.DataKeys[row.RowIndex].Value.ToString(), out branchID);
        //            selectedBranchList.Add(branchID);
        //        }
        //    }
        //}

        //if (selectedBranchList.Count > 0)
        //{
        //    string commaDelimitedBranchID = string.Empty;
        //    foreach (int selectedBranchID in selectedBranchList)
        //    {
        //        commaDelimitedBranchID += selectedBranchID.ToString() + ",";
        //    }

        //    if (!string.IsNullOrEmpty(commaDelimitedBranchID))
        //    {
        //        commaDelimitedBranchID = commaDelimitedBranchID.Substring(0, commaDelimitedBranchID.Length - 1);
        //        if(!string.IsNullOrEmpty(commaDelimitedBranchID))
        //        {
        //            //if (masterHelper == null) masterHelper = new MasterHelper();
        //            //if (masterHelper.DeleteBranches(commaDelimitedBranchID))
        //            //{
        //                LoadDataSource();
        //            //}
        //        }
        //    }
        //}

        //mpeViewBranches.Show();
    }

    #endregion

    #region PRIVATE METHODS

    private bool InsertBranch()
    {
        bool result = false;
        DateTime entryDate = new DateTime();
        //string branchCodePrefix = string.Empty;
        int branchCodeNumber = 0;

        try
        {
            using (RelightDBEntities context = new RelightDBEntities())
            {
                if (!context.Branches.Any(x => x.BranchName.ToUpper().Trim().Equals(tbBranchName.Text.ToUpper().Trim())))
                {
                    //GetBranchCodeSetup(context, ref branchCodePrefix, ref branchCodeNumber);
                    //if (!string.IsNullOrEmpty(branchCodePrefix) && branchCodeNumber > 0)
                    UniqueCodeSetup codeSetup = DefaultHelper.GetUniqueCodeSetup(context, UniqueCodeType.BranchCode);                    
                    if(codeSetup !=null && !string.IsNullOrEmpty(codeSetup.Prefix) && codeSetup.LastUniqueNumber >= 0)
                    {
                        branchCodeNumber = codeSetup.LastUniqueNumber + 1;
                        Branches branches = new Branches();
                        branches.BranchCode = DefaultHelper.GenerateRelightUniqueCode(codeSetup.Prefix, branchCodeNumber, string.Empty);
                        branches.BranchName = tbBranchName.Text;
                        branches.BranchAddress = tbAddress.Text;
                        branches.BranchPhone1 = tbPhone1.Text;
                        branches.BranchPhone2 = tbPhone2.Text;
                        entryDate = DateTime.Now;
                        branches.EntryDate = entryDate;
                        branches.ModifyDate = entryDate;

                        //Insert new branch details
                        context.AddToBranches(branches);

                        //Update Branch setup
                        int branchCodeID = UniqueCodeType.BranchCode.GetHashCode();
                        context.Setup.FirstOrDefault(x => x.ID == branchCodeID).IntValue = branchCodeNumber;

                        context.SaveChanges();

                        Utility.ShowMsgDiv(divMsg, "Data saved successfully.", true);
                        ResetForm();
                        //gvBranches.DataBind();
                        LoadDataSource(context);
                        result = true;
                    }
                    else
                        Utility.ShowMsgDiv(divErr, "BranchCode setup not found.", true);
                }
                else
                {
                    Utility.ShowMsgDiv(divErr, "Branch name already exists.", true);
                }
            }
        }
        catch (Exception ex)
        {
            result = false;
            Utility.ShowMsgDiv(divErr, ex.Message + "\r\n" + ex.InnerException, true);
        }
        finally
        {
            GC.Collect();
        }    
        return result;
    }

    private bool UpdateBranch(int branchID)
    {
        if (branchID <= 0) throw new ArgumentNullException("branchID");
        bool result = false;
        try
        {
            using (RelightDBEntities context = new RelightDBEntities())
            {
                if (!context.Branches.Any(x => x.BranchName.ToUpper().Trim().Equals(tbBranchName.Text.ToUpper().Trim()) && x.BranchID != branchID))
                {
                    Branches branch = context.Branches.FirstOrDefault(x => x.BranchID == branchID);
                    if (branch != null)
                    {
                        branch.BranchName = tbBranchName.Text;
                        branch.BranchAddress = tbAddress.Text;
                        branch.BranchPhone1 = tbPhone1.Text;
                        branch.BranchPhone2 = tbPhone2.Text;
                        context.SaveChanges();

                        Utility.ShowMsgDiv(divMsg, "Data saved successfully.", true);
                        ResetForm();
                        //gvBranches.DataBind();
                        LoadDataSource(context);
                        result = true;
                    }
                }
                else
                {
                    Utility.ShowMsgDiv(divErr, "Branch name already exists.", true);
                }
            }
        }
        catch (Exception ex)
        {
            result = false;
            Utility.ShowMsgDiv(divErr, ex.Message + "\r\n" + ex.InnerException, true);
        }
        finally
        {
            GC.Collect();
        }    
        return result;

    }

    //private void GetBranchCodeSetup(RelightDBEntities context, ref string prefix, ref int runningNumber)
    //{
    //    int branchCodeID = UniqueCodeType.BranchCode.GetHashCode();
    //    prefix = string.Empty;
    //    runningNumber = 0;
    //    Setup branchSetup = context.Setup.FirstOrDefault(x => x.ID == branchCodeID);
        
    //    if (branchSetup != null)
    //    {
    //        XElement xRoot = XElement.Parse(branchSetup.XmlValue);
    //        if (xRoot.Element("Prefix") != null)
    //            prefix = xRoot.Element("Prefix").Value;

    //        runningNumber = branchSetup.IntValue.Value + 1;
    //    }
    //}

    private void LoadDataSource(RelightDBEntities context)
    {
        //sdsBranches.SetConnString();
        //sdsBranches.SetSelectCommand(false, "GetAllBranch", null);

        //using (RelightDBEntities context = new RelightDBEntities())
        //{
            IList<Branches> branchList = context.Branches.ToList<Branches>();
            gvBranches.DataSource = branchList;
            gvBranches.DataBind();
        //}
    }

    private void LoadSelectedBranchDetails(int branchID)
    {
        try
        {
            Utility.HideMsgDiv(divMsg);
            Utility.HideMsgDiv(divErr);
            ResetForm();
            if (branchID > 0)
            {
                using (RelightDBEntities context = new RelightDBEntities())
                {
                    Branches branch = context.Branches.FirstOrDefault(x => x.BranchID == branchID);
                    if (branch != null)
                    {
                        tbBranchName.Text = branch.BranchName;
                        tbAddress.Text = branch.BranchAddress;
                        tbPhone1.Text = branch.BranchPhone1;
                        tbPhone2.Text = branch.BranchPhone2;
                        btnSave.CommandArgument = branchID.ToString();
                        btnSave.CommandName = "UpdateBranch";
                    }
                }
            }
            else
                throw new ArgumentNullException("branchID");
        }
        catch (Exception ex)
        {
            throw ex;
        }
        finally
        {
            GC.Collect();
        }
    }

    private void ResetForm()
    {    
        tbAddress.Text=string.Empty;
        tbBranchName.Text=string.Empty;
        tbPhone1.Text = string.Empty;
        tbPhone2.Text=string.Empty;
        btnSave.CommandArgument = "0";
        btnSave.CommandName = "InsertBranch";
    }

    #endregion
    
}